package com.hcbd.tdwt.ui.xingyu.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;


import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.AuthManger;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.BottomBar;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.base.ImgSendManager;
import com.hcbd.tdwt.base.ReceiveImgManager;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.base.bd.XyPdaBdSendChild;
import com.hcbd.tdwt.base.other.KeyBroadcastReceiver;
import com.hcbd.tdwt.base.other.ShutdownReceiver;
import com.hcbd.tdwt.ui.xingyu.service.ForegroundService;
import com.hcbd.tdwt.ui.xingyu.service.KeepLifeService;
import com.hcbd.tdwt.ui.xingyu.vo.PositionVo;
import com.hcbd.tdwt.util.ConvertData;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.pangu.bdsdk2021.bluetooth.BluetoothManage;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.fragment.HomeFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.MapFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.MessageFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.MyFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.SendSOSFragment_;
import com.hcbd.tdwt.ui.xingyu.vo.MenuIconVO;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

//星宇主页
@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @ViewById
    BottomBar bottomBar;
    @ViewById
    View mainLine;
    @ViewById
    RelativeLayout mainLL;
    @ViewById
    TextView test_1,test_2,test_3,test_4,test_5;
    private HomeFragment_ homeFragment;
    private MessageFragment_ messageFragment;
    private SendSOSFragment_ sendSOSFragment;
    private MapFragment_ mapFragment;
    private MyFragment_ myFragment;
    private AuthManger authManger;
    SharedPreferencesUtil sp;
    String TAG = "MainActivity";

    @AfterViews
    protected void init() {
        mainLL.setFitsSystemWindows(true);
        mainLine.setVisibility(View.GONE);
        authManger=AuthManger.getAuthManger();
        authManger.initDialog(this);
        sp=new SharedPreferencesUtil(this);
        homeFragment=new HomeFragment_();
        messageFragment=new MessageFragment_();
        sendSOSFragment=new SendSOSFragment_();
        mapFragment=new MapFragment_();
        myFragment=new MyFragment_();
        initShutdownReceiver();
        initBottomBar();
        initMenu();
        initSendMode();
        initNotification();
        initEncoderCodeRate();
        manageExternalPermission();
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            initGps();
        }
//        initGps();
        BdManager.getInstance().init(MainApp.getInstance());
        // 打开RN模块
        int source = sp.getAttributeInt(Constant.DATA_SOURCES);
        if(source==1){
//            ((XyPdaBdSendChild)BdToolFactory.getBdSendBase()).openRN();
        }

//        startService(new Intent(this, KeepLifeService.class));
        Intent mIntent = new Intent(this, ForegroundService.class);
        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O) {
            startForegroundService(new Intent(mIntent));
        }else{
            startService(mIntent);
        }



        test_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "位置转化: "+ ConvertData.posDFMCoverHex(113.212441));
            }
        });

        test_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int size=GlobalParams.positions.size();
                List<PositionVo> positions = new ArrayList<>();
                if(GlobalParams.locationReportFrequency==60){//一分钟
                    if(5>size){
                        positions=GlobalParams.positions;
                    }else{
                        positions=GlobalParams.positions.subList(size-4,size);
                    }
                }else if(GlobalParams.locationReportFrequency==120){//二分钟
                    positions=getPosition(size,2);
                }else if(GlobalParams.locationReportFrequency==180){//三分钟
                    positions=getPosition(size,3);
                }else if(GlobalParams.locationReportFrequency==300){//五分钟
                    positions=getPosition(size,5);
                }else if(GlobalParams.locationReportFrequency==600){//10分钟
                    positions=getPosition(size,10);
                }else if(GlobalParams.locationReportFrequency==1800){//30分钟
                    positions=getPosition(size,30);
                }else if(GlobalParams.locationReportFrequency==3600){//60分钟
                    positions=getPosition(size,60);
                }else if(GlobalParams.locationReportFrequency==7200){//120分钟
                    positions=getPosition(size,120);
                }
                Log.e(TAG, "位置转化: "+ ConvertToBdMsgTool.castUserMessageTo0x04N5(positions, (int) GlobalParams.locationReportFrequency));
            }
        });

    }

    public  List<PositionVo> getPosition(int size, int index){
        List<PositionVo> positions = new ArrayList<>();
        if(5>size){
            return GlobalParams.positions;
        }else if(size>=(index*4)){
            positions.add(GlobalParams.positions.get(0));
            positions.add(GlobalParams.positions.get(index));
            positions.add(GlobalParams.positions.get(index*2));
            positions.add(GlobalParams.positions.get(index*3));
            //positions.add(GlobalParams.positions.get(index*4));
        }else{
            for(int i=0;(i*index)<size;i++){
                positions.add(GlobalParams.positions.get(i*index));
            }
        }
        return positions;
    }
    private final int REQUEST_CODE=15;
    private void manageExternalPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + this.getPackageName()));
                startActivityForResult(intent, REQUEST_CODE);
            }else{
                checkPermission();
            }
        }else{
            checkPermission();
        }
    }
    public void checkPermission(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, permissionRequestCode);
        }else{
            authManger.initZipSdk();
        }
    }
    // 关机监听
    private BroadcastReceiver shutdownReceiver;
    private void initShutdownReceiver(){
        if(shutdownReceiver==null){
            shutdownReceiver=new ShutdownReceiver();
//            IntentFilter intent = new IntentFilter(Intent.ACTION_SHUTDOWN);
            IntentFilter intent = new IntentFilter(ShutdownReceiver.filter);
            registerReceiver(shutdownReceiver,intent);
        }
    }
    public void initBottomBar() {
        bottomBar.setContainer(R.id.fl_container)
                .setFirstChecked(0)
                .setTitleBeforeAndAfterColor("#FFFFFFFF", "#75FF5D")
                .addItem(homeFragment,
                        "首页", R.drawable.pre_main_home, R.drawable.on_main_home)
                .addItem(messageFragment,
                        "消息", R.drawable.pre_main_message, R.drawable.on_main_message)
                .addItem(sendSOSFragment,
                        "SOS", R.drawable.main_sos, R.drawable.main_sos)
                .addItem(mapFragment,
                        "地图", R.drawable.pre_main_map, R.drawable.on_main_map)
                .addItem(myFragment,
                        "我的", R.drawable.pre_main_my, R.drawable.on_main_my).buildTwo();

        bottomBar.setOnSwitchListener(currentFragment -> {
            if (currentFragment instanceof HomeFragment_) {
                ((HomeFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof MessageFragment_) {
                ((MessageFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof SendSOSFragment_) {
                ((SendSOSFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof MapFragment_) {
                ((MapFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof MyFragment_) {
                ((MyFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE){
            checkPermission();
        }else if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constant.TO_OPEN_GPS_REQUEST_CODE) {//开启GPS，重新添加地理监听
                if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    initGps();
                }
//                initGps();
                hideWarnDialog();
            }else if(requestCode ==AuthManger.PIC_SC_CODE||requestCode ==AuthManger.VO_SC_CODE){
                authManger.setResult(requestCode,resultCode,data);
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (requestCode == Constant.TO_OPEN_GPS_REQUEST_CODE) {//取消开启GPS
                toast("不开启GPS导致某些功能无法使用！");
            }
        }
    }

    private void initGps() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showWarnDialog("请打开手机GPS定位，\n否则APP将不能正常使用", view -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constant.TO_OPEN_GPS_REQUEST_CODE);
                hideWarnDialog();
            });
        } else {
            //初始化定位sdk
            MainApp.getInstance().initMap();
            MainApp.getInstance().initSystemLocation();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == permissionRequestCode) {
            authManger.initZipSdk();
            MainApp.getInstance().initMap();
            MainApp.getInstance().initSystemLocation();
        }
    }
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }
    @Override
    protected void onDestroy() {
        stopService(new Intent(this, ForegroundService.class));
        if(shutdownReceiver!=null){unregisterReceiver(shutdownReceiver);Log.e(TAG, "注销关机监听");}
//        ((XyPdaBdSendChild)BdToolFactory.getBdSendBase()).closeRN();
        BdToolFactory.getBdSendBase().close(this);
        MainApp.getInstance().closeSystemLocation();
        if(MainApp.getInstance().wakeLock!=null){
            MainApp.getInstance().wakeLock.release();
        }
        super.onDestroy();
    }



    public void initEncoderCodeRate(){
        int currentIndex =sp.getAttributeInt(Constant.ENCODER_RATE);
        if(currentIndex==-1){
            sp.addAttribute(Constant.ENCODER_RATE,3);
            Constant.encoderCodeRate=3;
        }else{
            Constant.encoderCodeRate=currentIndex;
        }

    }
    //默认初始化菜单
    public void initMenu(){
        List<MenuIconVO> list= SQLite.select().from(MenuIconVO.class).queryList();
        if(0==list.size()){
            //Log.e("菜单","初始化");
            MenuIconVO menuIconVO=new MenuIconVO();
            menuIconVO.menuName="发送消息";
            menuIconVO.index=1;
            menuIconVO.iconType="messageImg";
            menuIconVO.isShow=1;
            menuIconVO.insert();

            MenuIconVO menuIconVO2 =new MenuIconVO();
            menuIconVO2.menuName="添加联系人";
            menuIconVO2.index=2;
            menuIconVO2.iconType="contactImg";
            menuIconVO2.isShow=1;
            menuIconVO2.insert();

            MenuIconVO menuIconVO3=new MenuIconVO();
            menuIconVO3.menuName="北斗设备";
            menuIconVO3.index=3;
            menuIconVO3.iconType="bdEquipmentImg";
            menuIconVO3.isShow=1;
            menuIconVO3.insert();

            MenuIconVO menuIconVO4=new MenuIconVO();
            menuIconVO4.menuName="指挥中心";
            menuIconVO4.index=4;
            menuIconVO4.iconType="commandCenterImg";
            menuIconVO4.isShow=1;
            menuIconVO4.insert();

            MenuIconVO menuIconVO5=new MenuIconVO();
            menuIconVO5.menuName="报平安";
            menuIconVO5.index=5;
            menuIconVO5.iconType="okImg";
            menuIconVO5.isShow=1;
            menuIconVO5.insert();
            MenuIconVO menuIconVO7=new MenuIconVO();
            menuIconVO7.menuName="定位信息";
            menuIconVO7.index=6;
            menuIconVO7.iconType="bdLocationImg";
            menuIconVO7.isShow=1;
            menuIconVO7.insert();
            MenuIconVO menuIconVO6 = new MenuIconVO();
            menuIconVO6.menuName = "上报设置";
            menuIconVO6.index = 7;
            menuIconVO6.iconType = "locationUploadImg";
            menuIconVO6.isShow = 1;
            menuIconVO6.insert();
        }
    }
    //默认消息设置
    public void initNotification(){
        if("".equals(sp.getAttribute(Constant.SWITCH_BG_NOTIFICATION))){
            sp.addAttribute(Constant.SWITCH_BG_NOTIFICATION,Constant.Y);
        }else{
            Constant.bg_not_isOpen=sp.getAttribute(Constant.SWITCH_BG_NOTIFICATION);
        }

        if("".equals(sp.getAttribute(Constant.SWITCH_SOUND))){
            sp.addAttribute(Constant.SWITCH_SOUND,Constant.Y);
        }else{
            Constant.sound_isOpen=sp.getAttribute(Constant.SWITCH_SOUND);
        }

        if("".equals(sp.getAttribute(Constant.SWITCH_SHOCK))){
            sp.addAttribute(Constant.SWITCH_SHOCK,Constant.Y);
        }else{
            Constant.shock_isOpen=sp.getAttribute(Constant.SWITCH_SHOCK);
        }
        if("".equals(sp.getAttribute(Constant.SWITCH_UNREAD_MSG))){
            sp.addAttribute(Constant.SWITCH_UNREAD_MSG,Constant.Y);
        }else{
            Constant.unread_msg_isOpen=sp.getAttribute(Constant.SWITCH_UNREAD_MSG);
        }
    }
    //默认初始化发送模式
    public void initSendMode(){
        String mode=sp.getAttribute(Constant.MSG_MODE);
        if("".equals(mode)){
            sp.addAttribute(Constant.MSG_MODE,Constant.BLEND_MODE);
        }
    }

}
